package it.infodea.tapestrydea.pages;

import it.infodea.tapestrydea.RepositoryUploadedFileBean;
import it.infodea.tapestrydea.components.AjaxFileUpload;
import it.infodea.tapestrydea.services.jcr.nodes.wrappers.JcrFileNode;

import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.ValueFormatException;

import org.apache.tapestry5.FieldTranslator;
import org.apache.tapestry5.FieldValidator;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.IncludeJavaScriptLibrary;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.services.PropertyEditContext;

@IncludeJavaScriptLibrary("classpath:it/infodea/tapestrydea/pages/FilePropertyEditCallback.js")
public class FilePropertyEditBlocks {

	@Component
	private AjaxFileUpload upload;

	private JcrFileNode node = null;

	@Environmental
	private PropertyEditContext context;

	@SetupRender
	void setupRender() {
	}

	@SuppressWarnings("unchecked")
	public FieldValidator getUploadValidator() {
		return context.getValidator(upload);
	}

	@SuppressWarnings("unchecked")
	public FieldTranslator getUploadTranslator() {
		return context.getTranslator(upload);
	}

	public JcrFileNode getFile() throws ValueFormatException, PathNotFoundException, RepositoryException {
		checkNode();
		return node;
	}

	public boolean isNotNull() {
		checkNode();
		return node != null;
	}

	void checkNode() {
		RepositoryUploadedFileBean p = null;
		Object propertyValue = context.getPropertyValue();
		if (propertyValue instanceof RepositoryUploadedFileBean) {
			p = (RepositoryUploadedFileBean) propertyValue;
		}
		if (p != null) {
			node = p.getJcrFile();
		} else {
			node = null;
		}
	}

	public PropertyEditContext getContext() {
		return context;
	}

}
